package controllers

import (
	"commerce/common"
	"commerce/data"
	"commerce/model"
	"commerce/service"
	"commerce/utils"
	"html/template"
	"net/http"
	"path/filepath"
	"strconv"
	"strings"
)

func init() {

	common.Templates["brand"] = template.Must(template.ParseFiles(filepath.Join(common.CurDir, "views/templates/brand.html")))
	common.Templates["brand_edit"] = template.Must(template.ParseFiles(filepath.Join(common.CurDir, "views/templates/brand_edit.html")))
}

func ListBrand(w http.ResponseWriter, r *http.Request) {

	pageNo, err := strconv.Atoi(r.FormValue("pageNo"))
	if err != nil {
		pageNo = 1
	}
	pageSize, err := strconv.Atoi(r.FormValue("pageSize"))
	if err != nil {
		pageSize = common.PAGE_SIZE
	}

	name := strings.TrimSpace(r.FormValue("name"))

	var page, _ = data.PageBrand(pageNo, pageSize, name)

	if page == nil {
		common.Templates["5xx"].Execute(w, nil)
		return
	}
	// 分页条件查询使用
	var qs = r.URL.RawQuery

	index := strings.Index(r.RequestURI, "&pageNo=")
	var flag bool
	// 这一步操作是点击分页来的
	if index != -1 {
		qs = r.RequestURI[:index]
		flag = true
	} else {
		// 首次点击搜索按钮查询
		flag = false
		qs = "?"
		if len(name) > 0 {
			qs += "name=" + name
		}
	}
	if flag {
		page.Url = qs
	} else {
		page.Url = r.RequestURI + qs
	}

	common.Templates["brand"].Execute(w, page)
}

func AddBrandUIHandler(w http.ResponseWriter, r *http.Request) {

	list, _ := data.ListSubCategory()
	b := model.Brand{Categories: list}

	common.Templates["brand_edit"].Execute(w, b)
}

func GetBrandHandler(w http.ResponseWriter, r *http.Request) {

	id, err := strconv.Atoi(r.FormValue("id"))
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	b, err := data.GetBrandById(id)
	if err != nil {
		common.Templates["5xx"].Execute(w, err.Error())
		return
	}
	list, _ := data.ListSubCategory()
	b.Categories = list
	common.Templates["brand_edit"].Execute(w, b)
}

func AddOrEditBrandHandler(w http.ResponseWriter, r *http.Request) {

	var id = 0
	idVal := r.PostFormValue("id")
	if len(idVal) > 0 {
		id, _ = strconv.Atoi(idVal)
	}
	brandName := r.PostFormValue("brandName")
	description := r.PostFormValue("description")
	firstLetter := r.PostFormValue("firstLetter")
	sort, _ := strconv.Atoi(r.PostFormValue("sort"))
	categories := r.PostForm["categories"]
	var logo = ""
	f, header, err := r.FormFile("logo")
	var needUpdateCategory = true
	var bp *model.Brand
	// 更新操作
	if id > 0 {
		bp, _ = data.GetBrandById(id)
		if bp != nil {
			if len(bp.OwnCategories) == len(categories) {
				m := make(map[string]bool, len(categories))
				for _, c := range categories {
					m[c] = true
				}
				for _, c := range bp.OwnCategories {
					if f, ok := m[strconv.Itoa(c.Id)]; ok && f {
						needUpdateCategory = false
						continue
					} else {
						// 还是需要更新关联的类别
						needUpdateCategory = true
						break
					}
				}
			}
		}
	}
	// 如果用户上传了图片
	if err == nil && f != nil {
		// 先上传新图片
		uploadedPath, err := utils.Upload(f, header.Filename)
		if err != nil {
			common.Error.Printf("upload brand logo img failed, filename:%s, err:%v", header.Filename, err)
		} else {
			logo = uploadedPath
			// 更新操作
			if id > 0 {
				// 删除老的图片(如果有)
				if bp != nil && len(bp.Logo) > 0 {
					fns := strings.LastIndex(bp.Logo, "/")
					if fns > -1 {
						utils.Delete(bp.Logo[fns+1:])
					}
				}
			}
		}
	}
	b := model.Brand{Id: id, Name: brandName, Description: description, FirstLetter: firstLetter, Sort: sort, Logo: logo}
	if id <= 0 {
		id, err = service.AddBrand(b, categories)
	} else {
		if !needUpdateCategory {
			categories = nil
		}
		id, err = service.UpdateBrand(b, needUpdateCategory, categories)
	}
	//重定向到列表
	http.Redirect(w, r, "/commerce/api/v2/brand/list", http.StatusFound)
}

func UpdateBrandStatusHandler(w http.ResponseWriter, r *http.Request) {

	id, err := strconv.Atoi(r.FormValue("id"))
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
    status, err := strconv.Atoi(r.FormValue("status"))
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	if status != 0 && status != 1 {
		common.Templates["5xx"].Execute(w, "无效状态")
		return
	}
	data.UpdateBrandStatus(id, status)
    
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
}
